package cn.tqfeiyang.springplus.framework.security;

import cn.tqfeiyang.springplus.framework.toolkit.JsonUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * JWT服务。
 *
 * @author tqfeiyang
 * @since 2024-07-19
 */
@Component
public class JwtTokenService {

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Value("${jwt.expirationInMs}")
    private int jwtExpirationInMs;

    public String build(AuthenticationUserDetails userDetails) {
        return build(new JwtTokenSubject(
                userDetails.getUsername(),
                userDetails.getUuid()
        ));
    }

    public String build(JwtTokenSubject subject) {
        return Jwts.builder()
                .setSubject(JsonUtils.toJsonString(subject))
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpirationInMs))
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
    }

    public JwtTokenSubject parse(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(jwtSecret)
                .parseClaimsJws(token)
                .getBody();
        return parse(claims);
    }

    public JwtTokenSubject parse(Claims claims) {
        return JsonUtils.parseObject(claims.getSubject(), JwtTokenSubject.class);
    }

}
